package com.jeecg.modules.jmreport.test;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    /**
     * 计算字符串的MD5值
     */
    public static String md5(String input) {
        if (input == null) {
            return null;
        }

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            // 将字节数组转换为十六进制字符串
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);

            // 补齐前导零
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证输入的字符串与MD5值是否匹配
     */
    public static boolean verify(String input, String md5Hash) {
        if (input == null || md5Hash == null) {
            return false;
        }
        String inputHash = md5(input);
        return md5Hash.equalsIgnoreCase(inputHash);
    }
}